package lk.util;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.io.IOException;

/**
 * FTP 对象创建工厂
 *
 */
public class FtpClientFactory extends BasePooledObjectFactory<FTPClient> {

    public FtpClientFactory() {}

    /**
     * 新建对象
     */
    @Override
    public FTPClient create() throws Exception {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(lk.util.FtpUtil.FTP_TIME_OUT);
        try {
            ftpClient.connect(lk.util.FtpUtil.FTP_ADDRESS, lk.util.FtpUtil.FTP_PORT);
            boolean result = ftpClient.login(lk.util.FtpUtil.FTP_USERNAME, lk.util.FtpUtil.FTP_PASSWORD);
            if (!result) {
                throw new Exception("ftpClient登陆失败! userName:" + lk.util.FtpUtil.FTP_USERNAME + " ; password:" + lk.util.FtpUtil.FTP_PASSWORD);
            }
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setBufferSize(lk.util.FtpUtil.FTP_BUFFER_SIZE);
            ftpClient.setControlEncoding("GBK");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }

    @Override
    public PooledObject<FTPClient> wrap(FTPClient ftpClient) {
        return new DefaultPooledObject<>(ftpClient);
    }

    /**
     * 销毁对象
     */
    @Override
    public void destroyObject(PooledObject<FTPClient> p) throws Exception {
        FTPClient ftpClient = p.getObject();
        ftpClient.logout();
        super.destroyObject(p);
    }
}